<template>
    <div class="camera-container">
      <!-- 打开摄像头按钮 -->
      <button 
        v-if="!isCameraOpen && !photo" 
        @click="openCamera" 
        class="btn"
      >
        打开摄像头
      </button>
  
      <!-- 实时视频显示 -->
      <video 
        ref="videoElement" 
        v-show="isCameraOpen" 
        autoplay 
        class="video-preview"
      ></video>
  
      <!-- 拍照按钮 -->
      <button 
        v-if="isCameraOpen" 
        @click="capturePhoto" 
        class="btn capture-btn"
      >
        拍摄
      </button>
  
      <!-- 照片预览和操作 -->
      <div v-if="photo" class="preview-container">
        <img :src="photo" alt="拍摄的图片" class="photo-preview">
        <div class="action-btns">
          <button @click="retakePhoto" class="btn retake-btn">重拍</button>
          <button @click="sendToBackend(photo)" class="btn download-btn">开始验证</button>
        </div>
      </div>
    </div>
  </template>
  
  <script>
  export default {
    data() {
      return {
        isCameraOpen: false,  // 摄像头开启状态
        photo: null,         // 照片数据URL
        mediaStream: null,    // 媒体流对象
        score: 0,
      };
    },
    methods: {
    
      // 打开摄像头
      async openCamera() {
        try {
          // 请求摄像头权限
          const stream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode: "user" } // 前置摄像头（environment 后置）
          });
          
          // 释放之前的流（如果存在）
          if (this.mediaStream) {
            this.mediaStream.getTracks().forEach(track => track.stop());
          }
          
          // 初始化视频元素
          this.mediaStream = stream;
          const video = this.$refs.videoElement;
          video.srcObject = stream;
          await video.play();
          this.isCameraOpen = true;
          
        } catch (error) {
          console.error("摄像头访问失败:", error);
          alert("无法访问摄像头，请检查权限和连接！");
        }
      },
  
      // 拍摄照片
      capturePhoto() {
        const video = this.$refs.videoElement;
        const canvas = document.createElement('canvas');
        
        // 设置画布尺寸与视频一致
        canvas.width = video.videoWidth;
        canvas.height = video.videoHeight;
        
        // 绘制当前帧到画布
        canvas.getContext('2d').drawImage(video, 0, 0);
        this.photo = canvas.toDataURL('image/png');
        // 发送图片并关闭摄像头
        this.sendToBackend(this.photo); // 发送图片到后端
        this.isCameraOpen = false;
        this.mediaStream.getTracks().forEach(track => track.stop());
      },

      // 上传照片到后端
      async sendToBackend(base64Data) {
        const currentTime = new Date().toLocaleString('zh-CN', { 
        year: 'numeric',
        month: '2-digit',
        day: '2-digit',
        hour: '2-digit',
        minute: '2-digit',
        second: '2-digit'
      });
        try {
            const response = await fetch('http://localhost:8088/face-recognition', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({  image: base64Data.split(',')[1]  }) // 提取纯base64编码 
            });
            const result = await response.json(); 
            console.log(result.data);
            if (result.data >= 50) {
                alert('签到成功，'+`当前签到时间为${currentTime}`); 
            }else{alert('签到失败，请重新签到');}
        } 
        catch (error) {
            console.error(' 上传失败:', error);
            alert('人脸识别服务异常');
        }
    },

      // 重拍照片
      retakePhoto() {
        this.photo = null;
        this.openCamera();
      },
  
  
    },
    
    // 组件销毁前清理资源
    beforeDestroy() {
      if (this.mediaStream) {
        this.mediaStream.getTracks().forEach(track => track.stop());
      }
    }
  };
  </script>
  
  <style>
  .camera-container {
  text-align: center;
  margin: 20px;
}

.video-preview {
  width: 100%;
  max-width: 500px;
  border: 2px solid #ddd;
  border-radius: 8px;
  margin: 10px 0;
}

.photo-preview {
  width: 100%;
  max-width: 500px;
  border: 2px solid #ddd;
  border-radius: 8px;
  margin: 10px 0;
}

.btn {
  padding: 10px 20px;
  margin: 5px;
  border: none;
  border-radius: 5px;
  cursor: pointer;
  background-color: #4CAF50;
  color: white;
  transition: background 0.3s;
}

.btn:hover {
  background-color: #45a049;
}

.capture-btn {
  background-color: #f44336;
}

.capture-btn:hover {
  background-color: #da190b;
}

.retake-btn {
  background-color: #2196F3;
}

.download-btn {
  background-color: #9C27B0;
}

.action-btns {
  margin-top: 10px;
}
  </style>